package com.zxbit.uangstore.permission;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zxbit.uangstore.R;
import com.zxbit.uangstore.utils.ToastUtils;

import io.reactivex.functions.Consumer;

@SuppressLint("CheckResult")
public class Permission {
    private IPermisson permisson;
    private AppCompatActivity activity;

    public Permission(AppCompatActivity activity, IPermisson permisson) {
        this.activity = activity;
        this.permisson = permisson;
    }

    /**
     * 获取相关权限
     */
    public void requestAll() {
        RxPermissions rxPermissions = new RxPermissions(activity);
        final String[] permissions = {
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        };
        rxPermissions.request(permissions).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    permisson.onPermissonSuccess(1);
                } else {
                    permissonError();
                }
            }
        });
    }

    /**
     * 跳转到设置
     */
    private void jumpSettings() {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", activity.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", activity.getPackageName());
        }
        activity.startActivity(intent);
    }

    /**
     * 权限获取不成功
     */
    private void permissonError() {
        ToastUtils.showShort(activity, activity.getResources().getString(R.string.get_permission_failure_hint));
        jumpSettings();
    }
}
